home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C24 / Statcast.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.7 KB  |  65 lines

  1. //: C24:Statcast.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Examples of static_cast
  7.  
  8. class Base { /* ... */ };
  9. class Derived : public Base {
  10. public:
  11.   // ...
  12.   // Automatic type conversion:
  13.   operator int() { return 1; }
  14. };
  15.  
  16. void func(int) {}
  17.  
  18. class Other {};
  19.  
  20. int main() {
  21.   int i = 0x7fff; // Max pos value = 32767
  22.   long l;
  23.   float f;
  24.   // (1) typical castless conversions:
  25.   l = i;
  26.   f = i;
  27.   // Also works:
  28.   l = static_cast<long>(i);
  29.   f = static_cast<float>(i);
  30.  
  31.   // (2) narrowing conversions:
  32.   i = l; // May lose digits
  33.   i = f; // May lose info
  34.   // Says "I know," eliminates warnings:
  35.   i = static_cast<int>(l);
  36.   i = static_cast<int>(f);
  37.   char c = static_cast<char>(i);
  38.  
  39.   // (3) forcing a conversion from void* :
  40.   void* vp = &i;
  41.   // Old way produces a dangerous conversion:
  42.   float* fp = (float*)vp;
  43.   // The new way is equally dangerous:
  44.   fp = static_cast<float*>(vp);
  45.  
  46.   // (4) implicit type conversions, normally
  47.   // Performed by the compiler:
  48.   Derived d;
  49.   Base* bp = &d; // Upcast: normal and OK
  50.   bp = static_cast<Base*>(&d); // More explicit
  51.   int x = d; // Automatic type conversion
  52.   x = static_cast<int>(d); // More explicit
  53.   func(d); // Automatic type conversion
  54.   func(static_cast<int>(d)); // More explicit
  55.  
  56.   // (5) Static Navigation of class hierarchies:
  57.   Derived* dp = static_cast<Derived*>(bp);
  58.   // ONLY an efficiency hack. dynamic_cast is
  59.   // Always safer. However:
  60.   // Other* op = static_cast<Other*>(bp);
  61.   // Conveniently gives an error message, while
  62.   Other* op2 = (Other*)bp;
  63.   // Does not.
  64. } ///:~
  65.